package cn.itsource.org.service.impl;

import cn.itsource.basic.util.PageList;
import cn.itsource.org.domain.Employee;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.org.query.EmployeeQuery;
import cn.itsource.org.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 员工表的业务层实现类
 */
@Service
public class EmployeeServiceImpl implements IEmployeeService {

    /**
     * 注入持久层依赖
     */
    @Autowired
    private EmployeeMapper mapper;

    /**
     * 查询全部员工数据
     * @return
     */
    @Override
    public List<Employee> findAll() {
        return mapper.selectAll();
    }

    /**
     * 查询一个员工数据
     * @param id 主键id
     * @return
     */
    @Override
    public Employee findOne(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    /**
     * 分页查询
     */
    @Override
    public PageList<Employee> selectPage(EmployeeQuery query) {
        //1.传入分页参数
        PageHelper.startPage(query.getPage(),query.getRows());
        //2.调用通过模板类查询方法
        List<Employee> employees = mapper.selectAll();
        //3.实例化pageinfo并传入参数
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);
        //4.封装自定义的分页对象
        PageList<Employee> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());
        //5.返回分页信息
        return pageList;
    }

    /**
     * 新增或修改一个员工对象
     * @param employee  主键id
     */
    @Override
    public void saveOrUpdate(Employee employee) {
        //判断id是否为空
        if (employee.getId() == null){
            //如果id为空进行的是新增操作
            mapper.insertSelective(employee);
        }else {
            //根据主键id修改,只有设置了值的字段才会被新增进去
            mapper.updateByPrimaryKeySelective(employee);
        }
    }

    /**
     * 根据id删除
     * @param id 主键id
     */
    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    /**
     * 查询所有的经理
     * @return
     */
    @Override
    public List<Employee> findManagers() {
        return mapper.findManagers();
    }
}
